package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IntegratedInfoService {
    @Autowired
    private DruidDataSource druidDataSource;

    public List<Map<String, Object>> getC2VersionInfo() {
        List<Map<String, Object>> dataList = new ArrayList<>();
        String sql = "SELECT `ID`, `nodeName`, `buildTime`, `creatorName`, `versionNo`, `status`, `releaseStatus`, `pubStatus` FROM `c2_version_info`;";

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                // 获取字段值
                long id = rs.getLong("ID");
                String nodeName = rs.getString("nodeName");
                Timestamp buildTime = rs.getTimestamp("buildTime");
                String creatorName = rs.getString("creatorName");
                String versionNo = rs.getString("versionNo");
                int status = rs.getInt("status");
                int releaseStatus = rs.getInt("releaseStatus");
                int pubStatus = rs.getInt("pubStatus");

                // 使用 Map 来构造返回的 JSON 数据
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("id", id);
                dataMap.put("nodeName", nodeName);
                dataMap.put("buildTime", buildTime);
                dataMap.put("creatorName", creatorName);
                dataMap.put("versionNo", versionNo);
                dataMap.put("status", status);
                dataMap.put("releaseStatus", releaseStatus);
                dataMap.put("pubStatus", pubStatus);

                dataList.add(dataMap);

                System.out.println("ID: " + id + " Node Name: " + nodeName + " Build Time: " + buildTime +
                        " Creator Name: " + creatorName + " Version No: " + versionNo +
                        " Status: " + status + " Release Status: " + releaseStatus + " Pub Status: " + pubStatus);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataList;
    }

    public Map<String, Object> getC2VersionInfoByWeek() {
        // 创建返回数据的结构
        List<String> buildTimes = new ArrayList<>();
        List<Integer> statuses = new ArrayList<>();
        List<Integer> releaseStatuses = new ArrayList<>();
        List<Integer> pubStatuses = new ArrayList<>();

        String sql = "SELECT `buildTime`, `status`, `releaseStatus`, `pubStatus` FROM `c2_version_info`;";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-'W'w"); // 用于格式化日期为自然周的字符串

        System.out.println("Executing SQL: " + sql);

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            // 使用一个 Map 来按周分组并统计次数
            Map<String, Map<String, Integer>> weeklyStatsMap = new HashMap<>();

            while (rs.next()) {
                Timestamp buildTime = rs.getTimestamp("buildTime");
                int status = rs.getInt("status");
                int releaseStatus = rs.getInt("releaseStatus");
                int pubStatus = rs.getInt("pubStatus");

                System.out.println("Row data - buildTime: " + buildTime + ", status: " + status +
                        ", releaseStatus: " + releaseStatus + ", pubStatus: " + pubStatus);

                // 获取自然周
                String week = sdf.format(buildTime);

                // 初始化周数据的统计表
                weeklyStatsMap.putIfAbsent(week, new HashMap<>());
                Map<String, Integer> weekStats = weeklyStatsMap.get(week);

                // 累加统计数据
                weekStats.put("statusCount", weekStats.getOrDefault("statusCount", 0) + 1);
                weekStats.put("releaseStatusCount", weekStats.getOrDefault("releaseStatusCount", 0) + (releaseStatus == 1 ? 1 : 0));
                weekStats.put("pubStatusCount", weekStats.getOrDefault("pubStatusCount", 0) + (pubStatus == 1 ? 1 : 0));

                System.out.println("Updated week stats for " + week + ": " + weekStats);
            }

            // 将统计数据转化为 List<Map> 格式，便于返回
            for (String week : weeklyStatsMap.keySet()) {
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("week", week);
                dataMap.putAll(weeklyStatsMap.get(week));

                buildTimes.add(week);
                statuses.add(weeklyStatsMap.get(week).getOrDefault("statusCount", 0));
                releaseStatuses.add(weeklyStatsMap.get(week).getOrDefault("releaseStatusCount", 0));
                pubStatuses.add(weeklyStatsMap.get(week).getOrDefault("pubStatusCount", 0));

                System.out.println("Final weekly data for " + week + ": " + dataMap);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 打印汇总结果
        System.out.println("Final aggregated weekly data: " + buildTimes);
        System.out.println("Statuses: " + statuses);
        System.out.println("Release statuses: " + releaseStatuses);
        System.out.println("Publish statuses: " + pubStatuses);

        // 返回包含所有需要的数据
        Map<String, Object> response = new HashMap<>();
        response.put("buildTimes", buildTimes);
        response.put("statuses", statuses);
        response.put("releaseStatuses", releaseStatuses);
        response.put("pubStatuses", pubStatuses);

        return response;
    }


    public List<Map<String, Object>> getIntegrateComponentInfo() {
        List<Map<String, Object>> dataList = new ArrayList<>();
        String sql = "SELECT `ID`, `nodeName`, `buildTime`, `creatorName`, `versionNo`, `status` FROM `integrate_component`;";

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                // 获取字段值
                long id = rs.getLong("ID");
                String nodeName = rs.getString("nodeName");
                Timestamp buildTime = rs.getTimestamp("buildTime");
                String creatorName = rs.getString("creatorName");
                String versionNo = rs.getString("versionNo");
                int status = rs.getInt("status");

                // 使用 Map 来构造返回的 JSON 数据
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("id", id);
                dataMap.put("nodeName", nodeName);
                dataMap.put("buildTime", buildTime);
                dataMap.put("creatorName", creatorName);
                dataMap.put("versionNo", versionNo);
                dataMap.put("status", status);

                dataList.add(dataMap);

                System.out.println("ID: " + id + " Node Name: " + nodeName + " Build Time: " + buildTime +
                        " Creator Name: " + creatorName + " Version No: " + versionNo + " Status: " + status);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataList;
    }
}
